package com.zzl.mine.util;


import java.net.URLDecoder;
import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 3DES加密工具类
 */
public class Des3 {

	@SuppressWarnings("unused")
	private final static Logger logger = LoggerFactory.getLogger(Des3.class);

			// 密钥
	private  String secretKey = "njxeqgjypxfuomlianchuang";

	// 向量
	private final  String iv = "01234567";
	// 加解密统一使用的编码方式
	private final  String encoding = "utf-8";

	public Des3(String secretKey)
	{
		this.secretKey = secretKey;
	}
	
	public Des3(){}
	
	/**
	 * 3DES加密
	 * 
	 * @param plainText
	 *            普通文本
	 * @return
	 * @throws Exception
	 */
	public  String encode(String plainText) throws Exception {
		Key deskey = null;
		DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
		SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
		deskey = keyfactory.generateSecret(spec);

		Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
		IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
		cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
		byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding));
		return Base64.encode(encryptData);
	}

	/**
	 * 3DES解密
	 * 
	 * @param encryptText
	 *            加密文本
	 * @return
	 * @throws Exception
	 */
	public  String decode(String encryptText) throws Exception {
		Key deskey = null;
		DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
		SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
		deskey = keyfactory.generateSecret(spec);
		Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
		IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
		cipher.init(Cipher.DECRYPT_MODE, deskey, ips);

		byte[] decryptData = cipher.doFinal(Base64.decode(encryptText));

		String out = new String(decryptData, encoding);

		return out;
	}
	
	public static void main(String[] args) {
		try {
			System.out.println(new Des3("njxeqgjypxfuomlianchuang").decode(URLDecoder.decode("c2QRyoel9ss%3D", "utf-8") ));
//			System.out.println(URLEncoder.encode(new Des3("njxeqgjypxfuomlianchuang").encode("3"), "utf-8"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
